﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class KD_HS_INOUTSTOCKSUMMARYRPTInterfaceBusiness : KingdeeInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption GetSysReportData;
        //登录密匙
        public Base_ConfigParameter APISecret;
        public KD_HS_INOUTSTOCKSUMMARYRPTInterfaceBusiness()
        {
            this.InterfaceName = "存货收发汇总";
            //索引字段
            this.MapFields = GetMapField("GetSysReportData");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            GetSysReportData = this.interfaceOption.Where(x => x.OperateType == "GetSysReportData").First();
            //获取登录密匙
            APISecret = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='KingdeeAPISecret_LK'").First();
            //执行查询的事件
            this.QueryEvent += KD_HS_InOutStockInterfaceBusiness_QueryEvent;
            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }
        

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="KingDee_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, KingDee_NoQueryEventArgs KingDee_NoQueryEventArgs)
        {
            //API请求是否成功
            KingDee_NoQueryEventArgs.Success = KingDee_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void KD_HS_InOutStockInterfaceBusiness_QueryEvent(object sender, KingDee_QueryEventArgs queryEventArgs)
        {

            try
            {
                if (!APISecret.IsNullOrEmpty())
                {
                    //1.登录
                    HttpClient httpClient = new HttpClient();
                    httpClient.Url = APISecret.Name;
                    httpClient.Content = APISecret.Value;
                    var logResult = JObject.Parse(httpClient.Request())["LoginResultType"].Value<int>();
                    queryEventArgs.LogState = logResult;
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, KingDee_QueryEventArgs queryEventArgs)
        {

            //2.获取API接口调用的数据
            if (queryEventArgs.LogState == 1)
            {
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:K3ConnectionString");
                HS_InOutStockDTO data = new HS_InOutStockDTO();
                DateTime time = DateTime.Now.AddMonths(-1);
                data.FYear = time.ToString("yyyy");
                data.FENDYEAR = time.ToString("yyyy");
                data.FPeriod = time.ToString("MM");
                data.FEndPeriod = DateTime.Now.ToString("MM");
                //1.
                data.StartRow = queryEventArgs.Page.PageIndex;
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
            else
            {

            }
        }

        /// <summary>
        /// 查询执行完成的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, KingDee_QueryEventArgs queryEventArgs)
        {
            try
            {
                //将查询后的数据转换成对应格式的数据
                SysReportResult result = (SysReportResult)JsonConvert.DeserializeObject<SysReportResult>(queryEventArgs.ResultStr);
                if (result.Result.IsSuccess == true) queryEventArgs.Success = result.Result.IsSuccess;
                else queryEventArgs.Success = false;
                queryEventArgs.Rows = result.Result.Rows;
                //2.数量等于0完成查询
                if (queryEventArgs.Rows.IsNullOrEmpty()||queryEventArgs.Rows.Count == 0)
                {
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Page.PageIndex += 10000;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, KingDee_QueryEventArgs queryEventArgs)
        {

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
